package com.mac.macjetpackdemo.ui.search

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mac.macjetpackdemo.base.BaseViewModel
import com.mac.macjetpackdemo.data.SearchRepository
import com.mac.macjetpackdemo.data.model.SearchResult
import com.mac.macjetpackdemo.net.Status
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class SearchModel(private val searchRepository: SearchRepository) : BaseViewModel() {

    val searchLiveData = MutableLiveData<Status<SearchResult>>()

    fun getSearchDetail(keyword: String) {
//        viewModelScope.launch {
//            searchRepository.search(keyword, searchLiveData)
//        }
        viewModelScope.launch {
            net(
                {
                    searchLiveData.postValue(Status.loading(null))
                    async {
                        searchRepository.search(keyword)
                    }
                },
                success = {
                    searchLiveData.postValue(Status.success(it))
                },
                failed = fun(_: String, msg: String?) {
                    searchLiveData.postValue(Status.error(msg, null))
                }
            )
        }
    }

    fun getListByClassId(classId: String, start: String, num: String) =
        searchRepository.getTypeDetail(classId, start, num)

}